<?php

namespace App\Models;

use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Traits\AdminBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
/**
 * App\Models\Order
 *
 * @property int $id
 * @property int $user_id
 * @property string $username
 * @property string $mobile
 * @property string $address
 * @property string $street
 * @property int|null $parent_user_id
 * @property int|null $status 0 未安装 1 已安装
 * @property int $tag
 * @property int $number
 * @property string|null $memo
 * @property string|null $pay_time
 * @property string $pay_type
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property int|null $apply_status 0 未体现 1 已提现
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereApplyStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereMemo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereMobile($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereParentUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePayType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereStreet($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereTag($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereUsername($value)
 * @mixin \Eloquent
 * @property int $price
 * @property string $sn
 * @property int|null $commission
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCommission($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereSn($value)
 */
class Order extends Model
{
    CONST PAY_TYPE_ALIPAY = 2;
    CONST PAY_TYPE_WECHAT = 1;
    CONST PAY_TYPE_DOWN_LINE = 3;

    CONST APPLY_STATUS_WAIT = 0;
    CONST APPLY_STATUS_WAITING = 1;
    CONST APPLY_STATUS_PASS = 2;

    use AdminBuilder;

    public function product()
    {
       return  $this->belongsTo(Product::class);
    }

    public static function getSn($uid)
    {
        $time = strtotime('2017-07-16 02:12:02');
        $id = time() - $time;
        $key = 'order.sn';
        if (!Cache::has($key)) {
            Cache::forever($key,$id);
        }
        $id =  Cache::increment($key);
        return 'SN-' . time() . "-$uid-" . $id;
    }

    public static function getApplyMoney($uid, $order_id_list)
    {
        $orders = Order::whereParentUserId($uid)->where('pay_time', '>', '0')
            ->whereIn('id', explode(',', $order_id_list))
            ->get();
        $unapply = 0;
        if ($orders) {
            foreach ($orders as $order) {
                $data['product'] = [
                    'title' => '安装地址:' . $order->address . ' ' . $order->street,
                    'buy_time' => $order->pay_time,
                    'appleyStatusText' => $order->apply_status == 1 ? '已提现' : '未体现',
                    'applyStatus' => $order->apply_status,
                    'number' => '',
                    'image' => url($order->product->image),
                    'order_id' => $order->id,
                ];
                if ($order->apply_status === 0) {
                    $unapply += $order->commission;
                }
            }
        }
        return $unapply;
    }

    public static function isTestUser($id)
    {
//        return false;

        if (in_array($id,[1])) {
            return true;
        }
        return false;
    }

    public static function doPay(Order $order, $pay_type, $out_trade_no, $payAmount)
    {
        try {
            \DB::beginTransaction();
            app('log')->debug("doPay id ".$order->id,[
                'price'=>$order->price ,
                'user_id'=>$order->user_id ,
                'payAmount'=>$payAmount
            ]);
            $save = false;
            if (Order::isTestUser($order->user_id) || $order->price == $payAmount) {
                if ($pay_type == Order::PAY_TYPE_ALIPAY) {
                    $order->ali_out_trade_no = $out_trade_no;
                }else{
                    $order->out_trade_no = $out_trade_no;
                }
                $order->pay_time = date("Y-m-d H:i:s");
                $save = $order->save();
                app('log')->debug("doPay save order ".$order->id);

            }
            if ($save) {

                $result  = static::afterPayed($order);
                if ($result) {
                    app('log')->debug("doPay save success $result ".$order->id);

                    \DB::commit();
                    return true;
                }else{
                    app('log')->debug("doPay save rollBack $result ".$order->id);
                }
            }
            \DB::rollBack();
        } catch (\Exception $e) {
            \DB::rollBack();
        }
        return false;
    }

    public static function afterPayed(Order $order)
    {
        $has = UserProduct::whereOrderId($order->id)->first();
        if ($has) {
            app('log')->debug("UserProduct has ".$order->id);
            return true;
        }
        $userProduct = new UserProduct();
        $userProduct->order_id = $order->id;
        $userProduct->user_id = $order->user_id;
        $userProduct->product_id = $order->product->id;
        $result = $userProduct->save();
        app('log')->debug("UserProduct save ".$result);
        return $result;

    }


    public static function getOrderPrice($num)
    {
        $install_price = Product::$install_price;
        $open_acount_price = Product::$open_acount_price;
        $service_price = Product::$service_price;
        $discount_price = Product::$discount_price;
        $total = $install_price * $num + $open_acount_price + $service_price * $num;
        if ($num == 2) {
            $total = $total - $discount_price;
        } elseif ($num >= 3) {
            $total = $total - $discount_price * $num;
        }
        return $total;
    }

}
